package com.example.musicplayer.fragment

import android.animation.ObjectAnimator
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.example.musicplayer.R
import com.example.musicplayer.model.Music

/**
 * 音乐播放器页面
 */
class MusicPlayerFragment : Fragment() {
    private var musicTitleTextView: TextView? = null
    private var musicSingerTextView: TextView? = null
    private var musicCoverImageView: ImageView? = null
    private var musicProgress: SeekBar? = null
    private var mediaPlayer: MediaPlayer? = null
    private val handler = Handler()
    private var updateProgressRunnable: Runnable? = null
    private var currentTimeTextView: TextView? = null
    private var totalTimeTextView: TextView? = null
    private var rotation: ObjectAnimator? = null
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_music_player, container, false)

        musicTitleTextView = view.findViewById(R.id.music_title)
        musicSingerTextView = view.findViewById(R.id.music_singer)
        musicCoverImageView = view.findViewById(R.id.music_cover)
        musicProgress = view.findViewById(R.id.music_progress)
        currentTimeTextView = view.findViewById(R.id.music_current_time)
        totalTimeTextView = view.findViewById(R.id.music_total_time)

        musicProgress?.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    mediaPlayer!!.seekTo(progress)
                    updateTime()
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {
                handler.removeCallbacks(updateProgressRunnable!!)
            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {
                startUpdatingSeekBar()
            }
        })
        return view
    }

    /**
     * 启动封面图片旋转动画
     */
    private fun startCoverImageRotation() {
        // 这里的 rotation 报红不影响 别动
        rotation = ObjectAnimator.ofFloat(musicCoverImageView, "rotation", 0f, 360f).apply {
            duration = 3000
            repeatCount = ObjectAnimator.INFINITE
            interpolator = LinearInterpolator()
            start()
        }
    }

    /**
     * 暂停封面图片旋转动画
     */
    fun pauseCoverImageRotation() {
        rotation?.pause()
    }

    /**
     * 继续封面图片旋转动画
     */
    fun resumeCoverImageRotation() {
        rotation?.resume()
    }


    fun updatePlayerPage(music: Music, mediaPlayer: MediaPlayer?) {
        this.mediaPlayer = mediaPlayer
        musicTitleTextView!!.text = music.title
        musicSingerTextView!!.text = music.singer
        Glide.with(musicCoverImageView!!.context)
            .load(music.coverImgUrl)
            .into(musicCoverImageView!!)

        try {
            this.mediaPlayer!!.reset()
            this.mediaPlayer!!.setDataSource(music.src)
            this.mediaPlayer!!.setOnPreparedListener { mp: MediaPlayer? ->
                val totalDuration = this.mediaPlayer!!.duration
                musicProgress!!.max = totalDuration
                totalTimeTextView!!.text = formatTime(totalDuration)

                this.mediaPlayer!!.start()
                startUpdatingSeekBar()
                startCoverImageRotation()
            }
            this.mediaPlayer!!.prepareAsync()
        } catch (e: Exception) {
            Log.v("MusicPlayerFragment", e.toString())
        }
    }

    fun startUpdatingSeekBar() {
        updateProgressRunnable = object : Runnable {
            override fun run() {
                if (mediaPlayer != null && mediaPlayer!!.isPlaying) {
                    val currentPosition = mediaPlayer!!.currentPosition
                    musicProgress!!.progress = currentPosition
                    updateTime() // 更新时间显示
                    handler.postDelayed(this, 500)
                }
            }
        }
        handler.post(updateProgressRunnable as Runnable)
    }

    private fun updateTime() {
        if (mediaPlayer != null) {
            currentTimeTextView!!.text = formatTime(mediaPlayer!!.currentPosition)
            totalTimeTextView!!.text = formatTime(mediaPlayer!!.duration)
        }
    }

    private fun formatTime(millis: Int): String {
        val minutes = millis / 1000 / 60
        val seconds = millis / 1000 % 60
        return String.format("%02d:%02d", minutes, seconds)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (mediaPlayer != null) {
            mediaPlayer!!.release()
            mediaPlayer = null
        }
        handler.removeCallbacks(updateProgressRunnable!!)
    }
}